<?php


// Functin save data into variable
function _storage($name, $value = FALSE)
{
    static $noteStorage = array();
    if ($value)
        $noteStorage[$name] = $value;
    return $noteStorage[$name];
}



// Set active menu item
function m($code)
{
    _storage('menu.current', $code);
//    $_SESSION['menu']['current'] = $code;
}


function is_m($code) {
    return _storage('menu.current') == $code;
//    return $_SESSION['menu']['current'] == $code;
}


// Set active menu (on page report) item
function m_2($code)
{
    _storage('menu_2.current', $code);
//    $_SESSION['menu_2']['current'] = $code;
}


function is_m_2($code) {
    return _storage('menu_2.current') == $code;
//    return $_SESSION['menu_2']['current'] == $code;
}


function _log($msg = false)
{
static $logger;
if (!$msg)
	return $logger;
if (!$logger)
	$logger = new Logger("last_req", Logger::TYPE_REWRITE);
$logger->msg($msg);
}


function loadFunc($regExp = "*.php", $path = false){
if (!$path)
	$path = dirname(__FILE__);
foreach (glob($path."/".$regExp) as $entry)
	if (basename($entry) != basename(__FILE__)){
		_log("load ".substr($entry,strlen(_cfg("path"))));
		require_once $entry;			
	}	
}


loadFunc();	


/**
 * Gets value of configuration parameter
 * @param string $k parameter name
 * @return mixed parameter value
 */
function _cfg($k)
{
    static $cfg = array();
    if (!$cfg){
        // get common settings
        require_once('config/server.php');
        include 'config/common.php';

        // get modules settings
        $mods = glob($cfg['path'] . '_inc/mod/*', GLOB_ONLYDIR);
        foreach ($mods as $mod)
          	if (file_exists($mod.'/config/config.php')){
          		_log("load $mod/config/config.php");
        		include $mod.'/config/config.php';
        	}
        
    }    
    if ($cfg[$k])
        return $cfg[$k];
    if (strpos($k,".") !== false){
        $t =explode(".", $k);
        if (isset($cfg[$t[0]]) && is_array($cfg[$t[0]]) && isset($cfg[$t[0]][$t[1]]))
            return $cfg[$t[0]][$t[1]];
    }
}

/** Returns formatted mesage
 * @param  string $k message code
 * @param  mixed  $param array or string of message parameters
 * @return string formateed message
 */
function _fmt($k, $param=array())
{ 
    static $msg = array();
    if (!$msg){
        // get common settings
        include 'config/messages.php';
        // get modules messages
        $mods = glob(_cfg('path') . '_inc/mod/*', GLOB_ONLYDIR);
        foreach ($mods as $mod)
        	if (file_exists($mod.'/config/messages.php'))
            include $mod.'/config/messages.php';
    }
    if ($param && !is_array($param))
        $param = array($param);

    return vsprintf($msg[$k], $param);
}


/**
* Gets format date string
*
* @param date $date
* @param string $format
* @return string
*/
function _dformat($d, $format='')
{
   if (!$format)
       $format = _cfg('format.date');
   if (!is_numeric($d))
       $d = strtotime($d);
   if ($d <= 0)
       return '';			    
   return date($format, $d+_cfg('time.offset'));
}


/**
 * Gets part of full string with "..." in the end
 *
 * @param string $str
 * @param int $length
 * @return string
 */
function getPart($str = '', $length = 90)
{
	$str = htmlspecialchars_decode($str);
    if(mb_strlen($str) <= $length)
        return htmlspecialchars($str);
    return htmlspecialchars(mb_substr($str, 0, $length).' ...');
}

/**
 * Gets table name by alias. Checks for table renames
 *
 * @param string $name table name
 * @return string
 */
function _t($name)
{
    static $tbl = array();
    if (!$tbl)
        include 'config/tables.php';

    return (empty($tbl[$name]) ? $name : $tbl[$name]);
}


/**
 * Date ago
 */
function _dago($date_ts)
{
    $curr_date = time();
    $sec = $curr_date - $date_ts;        
    $dago = floor($sec/3600/24/30.42);
    if ($dago > 12) return 'more year ago';
    if ($dago > 0) return $dago.($dago==1?' month':' months').' ago';  
    $dago = floor($sec/3600/24/7);
    if ($dago > 0) return $dago.($dago==1?' week':' weeks').' ago';
    $dago = floor($sec/3600/24); 
    if ($dago > 0) return $dago.($dago==1?' day':' days').' ago';
    $dago = floor($sec/3600); 
    if ($dago > 0) return $dago.($dago==1?' hour':' hours').' ago'; 
    $dago = floor($sec/60); 
    if ($dago > 0) return $dago.($dago==1?' minute':' minutes').' ago';;
    return abs($sec).' seconds ago';
}

function _strJSON($arr)
{
	if (!is_array($arr))
		return '';
	return str_replace(array('"','ЬЬЬ,'),array('\"','","'),implode('ЬЬЬ,',$arr));		
}

/**
* Gets hash password
*
* @param string $data
* @return string
*/
function _pass($data){
    $code = $data;
    for ($i=0;$i<1000;$i++){
        $code = sha1($code.$i).sha1(md5($i.$code));
    }
    return $code;
}


/**
* Encoder
*
* @param string $data
* @return string
*/
function _encoder($data=""){
    $key = _cfg("key1");
    $alg = MCRYPT_BLOWFISH;
    $mode = MCRYPT_MODE_CBC;
    $encrypted_data = mcrypt_encrypt ($alg, $key, $data, $mode, $iv);
    return  base64_encode ($encrypted_data);
}

/**
* Decoder
*
* @param string $data
* @return string
*/
function _decoder($data){
    $key = _cfg("key1");
    $alg = MCRYPT_BLOWFISH;
    $mode = MCRYPT_MODE_CBC;
    return mcrypt_decrypt ($alg, $key, base64_decode($data), $mode);
}